/**
 * 
 * @returns 
 * @param
 * @description 不兼容IE浏览器
 */
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { default as api } from "./lib/api"
import React, { useState, useEffect, useRef, useMemo } from 'react'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import http from '@/utils/http'
import { UPLOADFILE_API, UPLOADIMG_API } from '@/api'
import { message } from 'antd'
import styles from "./styles/styles.module.scss"
// 富文本编辑器附件插入功能注册
import { Boot } from '@wangeditor/editor'
import attachmentModule from '@wangeditor/plugin-upload-attachment';
// import ImageFloatHover from "./plugin/image-float-right/image-float-right"
import { downloadFileFromOSS, upFileToOSS } from '../xx-AliyunOSSUpload/client/AliOss'
import { myModalMenuConf } from './plugin/modal/modal'
// Boot.registerMenu(ImageFloatHover);
Boot.registerModule(attachmentModule);
Boot.registerMenu(myModalMenuConf)
const WangEditor5 = ({
    value = "", onChange,
    warpStyle = {}, editorStyle = {}, toolBarStyle = {}
}) => {
    //自定义图床start
    const imageBedRef = useRef(null)
    const onSuccess = (result) => {
        console.log(result)

    }

    //自定义图床end

    // 工具栏配置
    const toolbarConfig = {
        insertKeys: {
            index: 0,
            keys: [
                "myModalMenu",
                'uploadAttachment',
            ],
        }
    }


    const [editor, setEditor] = useState(null);
    const [html, setHtml] = useState(value);
    const [insertList, setInsertList] = useState([]);//插入过的图片链接


    const triggerChange = (changedValue) => {
        onChange?.(changedValue);
    };
    const onEditorChange = (editor) => {
        const value = editor.getHtml();
        setHtml(value);
        triggerChange(value);
    };





    // 编辑器配置
    const editorConfig = {
        // 在编辑器中，点击选中“附件”节点时，要弹出的菜单
        hoverbarKeys: {
            attachment: {
                menuKeys: ['downloadAttachment'], // “下载附件”菜单
            },
        },
        // 菜单配置
        MENU_CONF: {
            // “上传附件”菜单的配置
            uploadAttachment: {
                server: '/api/upload', // 服务端地址
                timeout: 5 * 1000, // 5s

                fieldName: 'custom-fileName',
                meta: { token: 'xxx', a: 100 }, // 请求时附加的数据
                metaWithUrl: true, // meta 拼接到 url 上
                headers: { Accept: 'text/x-json' },

                maxFileSize: 10 * 1024 * 1024, // 10M

                onBeforeUpload(file = File) {

                    return file // 上传 file 文件
                    // return false // 会阻止上传
                },
                onProgress(progress = Number) {

                },
                onSuccess(file = File, res) {

                },
                onFailed(file = File, res) {
                    alert(res.message)

                },
                onError(file = File, err = Error, res) {
                    alert(err.message)

                },

                // // 上传成功后，用户自定义插入文件
                // customInsert(res: any, file: File, insertFn: Function) {
                //   console.log('customInsert', res)
                //   const { url } = res.data || {}
                //   if (!url) throw new Error(`url is empty`)

                //   // 插入附件到编辑器
                //   insertFn(`customInsert-${file.name}`, url)
                // },

                // 用户自定义上传
                async customUpload(file = File, insertFn = Function) {
                    const { type, size, name } = file
                    let metaData = {
                        fileName: name,
                        busiId: `contractEntity.contractCode`,
                        busiType: 'OBC'
                    }

                    let res = await upFileToOSS(file, metaData);
                    if (res.url) {
                        insertFn(`${res.name}`, res.url)
                    } else {
                        message.error("图片上传失败")
                    }


                },

                // // 自定义选择
                // customBrowseAndUpload(insertFn: Function) {
                //   alert('自定义选择文件，如弹出图床')
                //   // 自己上传文件
                //   // 上传之后用 insertFn(fileName, link) 插入到编辑器
                // },

                // 插入到编辑器后的回调
                onInsertedAttachment(elem) {

                },
            },
            // 图片上传配置
            uploadImage: {
                server: import.meta.env.VITE_APP_BASE_URL + UPLOADIMG_API, // 上传图片地址
                timeout: 30 * 1000, // 5s   

                fieldName: 'custom-fileName',
                // meta: { token: 'xxx', a: 100 },
                // metaWithUrl: true, // 参数拼接到 url 上
                headers: {
                    Accept: 'text/x-json',
                    Authorization: "Bearer "  //要带上token
                },

                maxFileSize: 10 * 1024 * 1024, // 10M

                base64LimitSize: 5 * 1024, // 5kb 以下插入 base64

                onBeforeUpload(files) {


                    return files // 返回哪些文件可以上传
                    // return false 会阻止上传
                },
                onProgress(progress) {

                },
                onSuccess(file, res) {

                },
                onFailed(file, res) {
                    alert(res.message)

                },
                onError(file, err, res) {
                    alert(err.message)

                },
                // // 自定义选择图片
                // customBrowseAndUpload(insertFn = Function) {
                //     imageBedRef.current.open()
                //     // TS 语法
                //     // customBrowseAndUpload(insertFn) {              // JS 语法
                //     // 自己选择文件
                //     // 自己上传文件，并得到图片 url alt href
                //     // 最后插入图片
                //     // insertFn(url, alt, href)
                // },

                // // 用户自定义插入图片
                // customInsert(res, insertFn) {
                //   console.log('customInsert', res)
                //   const imgInfo = res.data[0] || {}
                //   const { url, alt, href } = imgInfo
                //   if (!url) throw new Error(`Image url is empty`)

                //   // 自己插入图片
                //   console.log('自己插入图片', url)
                //   insertFn(url, alt, href)
                // },

                // 用户自定义上传图片
                async customUpload(file, insertFn) {


                    const { data, error } = await api.upload({ file: file });
                    if (error) {
                        message.error("上传失败：" + error)
                        return;
                    }
                    console.log("图片插入结果：", data)
                    insertFn(`${data.url}`
                        , new Date().getTime(), `${data.url}`
                    )
                },


            },
            // 插入图片配置
            insertImage: {
                onInsertedImage(imageNode) {
                    if (imageNode == null) return

                    const { src, alt, url, href } = imageNode
                    let temp = insertList;
                    temp.push(src)
                    setInsertList(temp)

                },
            },
            // 上传视频配置
            uploadVideo: {
                async customUpload(file, insertFn) {                  // JS 语法
                    //   file即选中的文件，自己实现上传 并得到url poster
                    http.upload({
                        url: import.meta.env.VITE_APP_BASE_URL + "UPLOADVIEDOAPI",
                        params: {
                            file: file
                        },
                        before: () => { },
                        success: res => insertFn(`${res.data.fileDirPath}`
                            , new Date().getTime(), `${res.data.fileDirPath}`
                        ),
                        failure: msg => message.error("上传失败：" + msg)
                    })
                }
            }
        }
    }


    useEffect(() => {
        return () => {
            if (editor == null) return;
            if (editor.destory) {
                editor.destory();
            }
            setHtml(null)
            // editor.destory();
            setEditor(null);
        }
    }, [editor])


    useEffect(() => {
        setHtml(value)
    }, [value])

    const [editorHeight, setEditorHeight] = useState(343);
    const toolBarRef = useRef();
    const editorRef = useRef();
    const boxRef = useRef();


    useEffect(() => {
        //获取boxRef高度，获取toolBarRef高度，两高度相减，得出editor高度
        setTimeout(() => {
            const boxHeight = boxRef?.current?.clientHeight;
            boxHeight && setEditorHeight(boxHeight - 80.57 - 20)
        }, 50)


    }, [])

    return (
        <>
            <div className={styles.wangEditor}
                ref={boxRef}
                style={{
                    ...warpStyle
                }} >
                <Toolbar
                    defaultConfig={toolbarConfig}
                    ref={toolBarRef}
                    editor={editor}
                    mode="default"
                    className='toolbar'
                    style={{ ...toolBarStyle }}
                />
                <Editor
                    ref={editorRef}
                    defaultConfig={editorConfig}
                    value={html}
                    className='wangEditor-container'
                    onCreated={setEditor}
                    onChange={onEditorChange}
                    mode={'default'}
                    style={{ height: editorHeight, ...editorStyle }}

                />
            </div>
        </>
    )
}


export default WangEditor5